package com.card.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.card.dao.CardInfoMapper;
import com.card.dto.WeChatSessionResponse;
import com.card.entity.CardInfo;
import com.card.service.WeChatAuthService;
import com.card.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Slf4j
@Service
public class WeChatAuthServiceImpl implements WeChatAuthService {

    private static final String APPID = "wxec7690b92384c7c5";
    private static final String SECRET = "fa4b70cec41ff96721d4b52535043cf0";
    private static final String AUTH_URL = "https://api.weixin.qq.com/sns/jscode2session";
    private final CardInfoMapper cardInfoMapper;

    public WeChatAuthServiceImpl(CardInfoMapper cardInfoMapper) {
        this.cardInfoMapper = cardInfoMapper;
    }


    @Override
    public Map<String, Object> wxLogin(String code) throws IOException {

        OkHttpClient client = new OkHttpClient();

        HttpUrl.Builder urlBuilder = Objects.requireNonNull(HttpUrl.parse(AUTH_URL)).newBuilder();
        urlBuilder.addQueryParameter("appid", APPID);
        urlBuilder.addQueryParameter("secret", SECRET);
        urlBuilder.addQueryParameter("js_code", code);
        urlBuilder.addQueryParameter("grant_type", "authorization_code");

        Request request = new Request.Builder()
                .url(urlBuilder.build())
                .build();

        try (Response response = client.newCall(request).execute()) {
            Assert.isTrue(response.isSuccessful(), "微信接口调用失败");

            String responseBody = response.body().string();
            WeChatSessionResponse sessionResponse = JSON.parseObject(responseBody, WeChatSessionResponse.class);

            Assert.isTrue(sessionResponse.getErrcode() == null, "微信接口错误: " + sessionResponse.getErrmsg());

            // 检查是否已经存在该用户
            LambdaQueryWrapper<CardInfo> cardInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            cardInfoLambdaQueryWrapper.eq(CardInfo::getOpenId, sessionResponse.getOpenid());
            CardInfo cardInfo = cardInfoMapper.selectOne(cardInfoLambdaQueryWrapper);
            Map<String, Object> map = new HashMap<>();
            map.put("token", JwtUtils.createToken(sessionResponse.getOpenid()));
            map.put("status", Objects.nonNull(cardInfo));
            return map;
        }
    }
}
